$(function () {
    $("#user_logo").click(function () {
        window.location.href = "/Lvscore_User_M/userWeb/views/accounterCenter/index.html"
    });
    $(".logo").click(function () {
        var url = window.location.href;
        if (url.indexOf("www.jifenguanggao.com") > 0) {
            window.location.href = "http://www.jifenguanggao.com/Advertiser_Mall/weijifen/home.html";
        } else {
            window.location.href = "http://192.168.3.67/Advertiser_Mall/weijifen/home.html";
        }
    });
    $("#logo").click(function () {
        var url = window.location.href;
        if (url.indexOf("www.jifenguanggao.com") > 0) {
            window.location.href = "http://www.jifenguanggao.com/Advertiser_Mall/weijifen/home.html";
        } else {
            window.location.href = "http://192.168.3.67/Advertiser_Mall/weijifen/home.html";
        }
    });
    $("#user_exit").click(function () {
        userExit();
    });
    userFilter();
    //判断是否出现滚动条
    //if (document.documentElement.clientHeight < document.documentElement.offsetHeight) {
    //    console.log("hight"+document.documentElement.clientHeight+"|"+document.documentElement.offsetHeight);
    //}else{
    //    console.log("lower"+document.documentElement.clientHeight+"|"+document.documentElement.offsetHeight);
    //}
});
/**
 * 跳转页面
 * @param type
 */
function goHome(type) {
    if (type == "register") {
        window.location.href = "/Lvscore_User_M/userWeb/views/register/registerTel.html";
    }
    else if (type == "accounterCenter") {
        window.location.href = "/Lvscore_User_M/userWeb/views/accounterCenter/index.html";
    }
    else if (type == "retrievePassword") {
        window.location.href = "/Lvscore_User_M/userWeb/views/retrievePassword/selectorMode.html";
    }
    else if (type == "ADadmin") {
        window.location.href = "/Lvscore_User_M/userWeb/views/ADadmin/accounterMoney/index.html";
    }
    else if (type == "myAD") {
        window.location.href = "/Lvscore_User_M/userWeb/views/myAD/applicationAD/index.html";
    }
}
function userExit() {
    var url = "/Lvscore_User_M/ajaxLogout";
    $.post(url, {}, function () {
        var cookie = new sweetCookie();
        cookie.setCookie("user", "", -1);
        var url2 = window.location.href;
        var url1 = "";
        if (url2.indexOf("www.jifenguanggao.com") > 0) {
            //window.location.href = "http://www.jifenguanggao.com/Advertiser_Mall/weijifen/home.html";
            url1 = "http://www.jifenguanggao.com/Advertiser_Mall/index/ajaxlogout";
        } else if (url2.indexOf("192.168.3.67") > 0) {
            //window.location.href = "http://192.168.3.67/Advertiser_Mall/weijifen/home.html";
            url1 = "http://192.168.3.67/Advertiser_Mall/index/ajaxlogout";
        }
        $.ajax({
            url: url1,
            type: 'POST',
            dataType: 'JSONP',
            error: function (e) {
                window.location.href = "/Lvscore_User_M";
            },
            success: function (data) {
                window.location.href = "/Lvscore_User_M";
            }
        });
    });


}
function getUser_C() {
    var cookie = new sweetCookie();
    var json = decodeBase64(cookie.getCookie("user"), 3);
    var user;
    if (json && json != "\"\"") {
        user = JSON.parse(decodeURIComponent(json));
    }
    return user;
}
//用户登录过滤器
function userFilter() {
    var url = window.location.href;
    if (url.split("/Lvscore_User_M/")[1] == "") {

    } else if (url.indexOf("/register/") <= 0 && url.indexOf("/retrievePassword/") <= 0) {
        var user = getUser_C();
        if (user) {
            $("#user_name").text(user.name);
            $("#user_id").text(user.id);
            $("#user_balance").text(user.balance);
            $("#user_logo").attr("src", user.image);
            getUnreadMsg(user);
        } else {
            flushUser();
        }
    }
}

function flushUser(href) {
    var url = "/Lvscore_User_M/ajaxGetUser";
    $.post(url, {}, function (data) {
        if (!data || data == "" || data == "\"\"") {
            userExit();
        }
        $("#user_name").text(data.name);
        $("#user_id").text(data.id);
        $("#user_balance").text(data.balance);
        $("#user_logo").attr("src", data.image);
        ajaxFlushUnread(data);
        if (href) {
            window.location.href = href;
        }
    });
}
/**
 * 获取用户信息未读条数
 */
function getUnreadMsg(user) {
    if (user.msgNum) {
        if ($("#msg_num").length <= 0) {
            $(".first").append("(<span style='margin: 0px' id='msg_num'>" + user.msgNum + "</span>)")
        } else {
            $("#msg_num").text(user.msgNum);
        }
    } else {
        ajaxFlushUnread(user);
    }
}
/**
 * 刷新用户信息未读条数
 */
function ajaxFlushUnread(user) {
    var url = "/Lvscore_User_M/msg/ajaxGetUnread";
    $.post(url, {}, function (data) {
        user.msgNum = data;
        var json = encodeBase64(encodeURIComponent(JSON.stringify(user)), 3);
        var cookie = new sweetCookie();
        cookie.setCookie("user", json, 30 * 60 * 1000);
        if (data && data > 0) {
            if ($("#msg_num").length <= 0) {
                $(".first").append("(<span id='msg_num'>" + data + "</span>)")
            } else {
                $("#msg_num").text(data);
            }
        } else {
            $(".first").html('<img src="/Lvscore_User_M/userWeb/static/images/letter_03.png" alt="">消息')
        }
    })
}
/**
 * 获取地址栏参数值
 * @param name 参数名
 * @returns
 */
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)return unescape(r[2]);
    return null;
}
function playAd() {
    $(".plays").click(function () {
        //console.log($(this).attr("ad_id"));
        var id = $(this).attr("ad_id");
        var appId = $(this).attr("app_id");
        var url = window.location.href;
        var url1 = "";
        if (url.indexOf("www.jifenguanggao.com") > 0) {
            url1 = "http://www.jifenguanggao.com/Advertiser_Mall/weijifen/detail_pages.html?id=" + id;
        } else {
            url1 = "http://192.168.3.67/Advertiser_Mall/weijifen/detail_pages.html?id=" + id;
        }
        if (isNotEmpty(appId)) {
            url1 = url1 + "&appId=" + appId
        }
        window.open(url1);
    });
}
function isEmail(email) {
    return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(email);
}
function isMobile(mobile) {
    return /^1[3|4|5|7|8]\d{9}$/.test(mobile);
}
function isPassword(password) {
    return /^[0-9a-zA-Z]{6,18}$/.test(password);
}
function isName(name) {
    return /^[\u4e00-\u9fa5A-Za-z0-9]{4,10}$/.test(name);
}
function isRealName(name) {
    return /^[\u4e00-\u9fa5]{2,10}$/.test(name);
}
function isBankCard(number) {//仍旧存在bug
    //todo 存在bug
    return /^(\d{16,19})$/.test(number);
}
function isMoney(money) {
    return /^((?!0+$)(?!0*\.0*$)\d{1,8}(\.\d{1,2})?)$/.test(money);
}

/**
 * 查询和更新用户支付密码状态
 *      使用方法：校验支付密码之前查询一次 无需传入参数 返回结果小于0则锁定
 *              校验支付密码之后调用此方法，传入支付密码校验状态（true/false)，返回剩余可输入次数（0-5）
 * @param session
 * @param status    密码是否输入正确  true / false  为空时获取用户支付密码状态（是否锁定）
 * @return
 * @throws Exception
 */
function ajaxGetPayPswTimes(status) {
    var status2 = "";
    var url = '/Lvscore_User_M/account/ajaxGetPayPswTimes';
    $.post(
        url,
        {'status': status},
        function (data) {
            status2 = data;
        },
        'json'
    );
    return status2;
}

/**
 * 验证输入的支付密码是否正确
 * @param oldPayPsw    用户输入的支付密码
 * @param fn    支付密码正确时需要执行的方法
 */
function ajaxValidateOldPayPsw(oldPayPsw, fn) {
    $.ajaxSettings.async = false;
    loading("努力加载中...");
    var status = ajaxGetPayPswTimes();
    if (status > 0) {
        var url = "/Lvscore_User_M/account/ajaxValidateOldPayPsw";
        $.post(
            url,
            {'oldPayPsw': oldPayPsw},
            function (data) {
                $(".loadingBox").hide();
                if (data == 1) {ajaxGetPayPswTimes
                    ajaxGetPayPswTimes(true);
                    fn();
                } else {
                    var time = ajaxGetPayPswTimes(false);
                    errorPsw(time);
                    //validateSpanMsg("oldPsd", "旧密码错误");
                }
            },
            "json"
        );
    } else {
        $(".loadingBox").hide();
        alertBox('支付密码锁定', '');
    }
    $.ajaxSettings.async = true;
}

/**
 * 支付密码错误时出现的弹窗
 * @param time 剩余可以输入支付密码的次数
 */
function errorPsw(time) {
    if ($("#errorPsw").length <= 0) {
        $("body").append(
            '<div id="errorPsw" class="paymentMiss border_radius">' +
            '<p class="errorInfm"><img src="" alt="">对不起，支付密码错误，你还有<span class="num red" style="margin:0px 5px;">' + time + '</span>次机会！请重新输入！</p>' +
            '<p class="btnbox">' +
            '<span onclick="hideBox()" class="certain btnBox handes inline-block">确定</span>' +
            '<a href="javascript:void(0)" onclick="forgotPayPsw()" class="btnBox">忘记密码</a>' +
            '</p>' +
            '</div>'
        );
    } else {
        $(".num").html(time);
    }
    $("#errorPsw").show();
    if (time == 0) {
        $(".errorInfm").html("对不起，已经连续输错<span class='red' style='margin:0px 5px;'>5</span>次支付密码,请3小时后再试！")
    }
}

function hideBox() {
    $("#errorPsw").hide();
}

/**
 * 证件校验
 * @param type
 * @param code
 * @returns {*}
 */
function isCredentials(type, code) {//0身份证  1护照  3军官证
    if (isNotEmpty(code)) {
        var tip = "";
        var pass = true;
        if (type == 0) {
            var city = {
                11: "北京",
                12: "天津",
                13: "河北",
                14: "山西",
                15: "内蒙古",
                21: "辽宁",
                22: "吉林",
                23: "黑龙江",
                31: "上海",
                32: "江苏",
                33: "浙江",
                34: "安徽",
                35: "福建",
                36: "江西",
                37: "山东",
                41: "河南",
                42: "湖北",
                43: "湖南",
                44: "广东",
                45: "广西",
                46: "海南",
                50: "重庆",
                51: "四川",
                52: "贵州",
                53: "云南",
                54: "西藏",
                61: "陕西",
                62: "甘肃",
                63: "青海",
                64: "宁夏",
                65: "新疆",
                71: "台湾",
                81: "香港",
                82: "澳门",
                91: "国外 "
            };
            if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
                tip = "身份证号格式错误";
                pass = false;
            }

            else if (!city[code.substr(0, 2)]) {
                tip = "身份证号校验错误";
                pass = false;
            }
            else {
                //18位身份证需要验证最后一位校验位
                if (code.length == 18) {
                    code = code.split('');
                    //∑(ai×Wi)(mod 11)
                    //加权因子
                    var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                    //校验位
                    var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                    var sum = 0;
                    var ai = 0;
                    var wi = 0;
                    for (var i = 0; i < 17; i++) {
                        ai = code[i];
                        wi = factor[i];
                        sum += ai * wi;
                    }
                    var last = parity[sum % 11];
                    if (parity[sum % 11] != code[17]) {
                        //tip = "校验位错误";
                        tip = "身份证号校验错误";
                        pass = false;
                    }
                }
            }
        } else if (type == 1) {
            if (!/^(P\d{7})|(G\d{8})$/.test(code)) {
                tip = "护照格式错误";
                pass = false;
            }
        } else if (type == 2) {
            if (!/^[a-zA-Z0-9]{7,21}$/.test(code)) {
                tip = "军官证格式错误";
                pass = false;
            }
        }
        //if (!pass) alertBox(tip, '');
        return tip;
    } else {
        return "输入证件号码不能为空";
    }
}
//弹窗
function alertBox(msg, error) {
    if ($(".mask").length <= 0) {
        $("body").append("<div class='mask'></div>");
    }
    if ($('#fixed-tel').length <= 0) {
        $("body").append("<div id='fixed-tel'></div>");
    }
    $('.mask').show();
    if (error == undefined)
        $('#fixed-tel').html(msg).show();
    else
        $('#fixed-tel').html('<span style="color:red">' + msg + '</span>').show();
    setTimeout(hide, 1000);
}
function hide() {
    $('.mask').hide();
    $('#fixed-tel').hide();
}
//text是弹窗的提示内容
function show(text) {
    $('.mask').show();
    $('#fixed-tel').html(text).show();
    setTimeout(hide, 1000);
}


function isNotEmpty(info) {
    if (info == null || info == undefined || info == '' || info == 'null' || info == "\"\"" || info == "\'\'")
        return false;
    else
        return true;
}

function stringUtil(info) {
    if (info == 'null' || info == null)
        return '';
    else
        return info;
}
//
//获取验证码倒计时
var countdown = 30;
function settime(val) {
    if (countdown == 0) {
        val.removeAttribute("disabled");
        val.value = "获取验证码";
        val.style.opacity = "1";
        countdown = 30;
        return;
    } else {
        val.setAttribute("disabled", true);
        val.style.opacity = "0.5";
        val.value = "重新发送(" + countdown + ")";
        countdown--;

    }
    setTimeout(function () {
        settime(val)
    }, 1000)
}
//获取单选按钮的值
function getRadioValue(name) {
    var radioObject = $('[name="' + name + '"]'), value;
    radioObject.each(function () {
        if ($(this)[0].checked) {
            value = $(this)[0].value;
        }
    });
    return value;
}

//加载等待效果
function loading(text) {
    if ($(".loadingBox").length <= 0) {
        $("body").append("<div class='loadingBox'></div> ");
    }
    $(".loadingBox").html(
        '<div class="loading">' +
        '   <img src="/Lvscore_User_M/userWeb/static/images/loading.gif" alt="" title="" style="width:30px;">' +
        '   <p class="inline-block loadingText">数据加载中,请稍等...</p>' +
        '</div>'
    );
    $(".loadingBox").show();
    $(".loadingText").text(text);
}
/**
 * 确认框弹出和关闭
 */
//function confirmBox(){
//    $(".mask").show();
//    $(".confirmBox").show();
//}
function confirmClose() {
    $(".mask").hide();
    $(".confirmBox").hide();
}
/**
 * 操作错误提示信息
 * @param id  提示span的id
 * @param msg 错误信息  msg为空或''时，清空span
 */
function validateSpanMsg(id, msg) {
    if (msg && msg != '') {
        $('#' + id).html('<span style="color: red;font-size: 11px;margin-right: 0px"> *' + msg + '</span>');
    } else {
        $('#' + id).html('');
    }
}
//实时监控输入框的值
function inputChange(ele1, ele2) {
    $(ele1).bind('input propertychange', function () {
        $(ele2).html("");
    })
}
/**
 * 获取用户来路url(referrer)
 */
function getUrl() {
    var url2 = document.referrer;
    var home = arguments[0].split('/')[0];
    if (isNotEmpty(url2)) {
        var host = window.location.host;
        url2 = url2.split('/Lvscore_User_M/userWeb/views/');
        var host_ = url2[0].split('//')[1];
        url2 = url2[1].split('.html')[0];
        if (host == host_) {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] == url2) {
                    return false;
                }
            }
        }
    }
    alertBox('操作异常，请重试', '');
    setTimeout(function () {
        goHome(home);
    }, 1500);
}

var sweetCookie = function () {
    var _this = this;
    _this.setCookie = function (key, value, time) {  //设置cookie;  time:毫秒
        var exp = new Date();
        exp.setTime(exp.getTime() + time);
        document.cookie = key + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/Lvscore_User_M";
    };
    _this.getCookie = function (key) {   //获取cookie;
        var arr, reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    };
    _this.delCookie = function (key) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = _this.getCookie(key);
        if (cval != null)
            document.cookie = key + "=" + cval + ";expires=" + exp.toGMTString();
    }
};

/**
 * 获取用户是否已经设置支付密码
 *      并根据返回值执行相应的函数
 */
function ajaxGetPayPswStatus(fn) {
    var url = "/Lvscore_User_M/account/ajaxGetPayPswStatus";
    $.post(
        url,
        function (data) {
            fn(data);
        },
        "json"
    );
}

//忘记密码页面
function forgotPayPsw() {
    window.location.href = '/Lvscore_User_M/userWeb/views/accounterCenter/changePaymentPassword.html';
}

//设置密码页面
function setPayPsw() {
    window.location.href = '/Lvscore_User_M/userWeb/views/accounterCenter/setPaymentPsd.html';
}

//获取文本值的长度 数字和英文为一个字符，汉字为两个字符
function getLength(info) {
    return info.replace(/[\u4E00-\u9fa5]/g, "**").length;
}
//超过字数限制，用...代替
function oversize(className, wordLength) {
    if ($("." + className).text().length >= wordLength) {
        var newText = $("." + className).text().substring(0, wordLength) + "...";
        $("." + className).html(newText);
    }
}
/**
 * 设置jQuery Ajax全局的参数
 */
function ajaxSetep() {
    $.ajaxSetup({
        type: "POST",
        timeout: 10000,
        error: function (jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
                case(500):
                    alertBox('服务器异常，请稍后重试', '');
                    break;
                case(401):
                    alertBox("未经授权：访问凭据无效", '');
                    break;
                case(403):
                    alertBox("无权限执行此操作", '');
                    break;
                case(408):
                    alertBox("请求超时，请检查您的网络", '');
                    break;
                default:
                    alertBox("请求超时，请检查您的网络", '');
            }
            if (isNotEmpty($("#get").length > 0)) {
                settime($("#get")[0]);
            }
        }
    });
}

/**
 * 截取过长的标题
 * @param name   内容
 * @param length 长度限制
 * @param start  头
 * @param end    尾
 * @returns {*}
 */
function getTitle(name, length, start, end) {
    if (!isNotEmpty(length)) {
        length = 25;
        start = 7;
        end = 7;
    }
    if (getLength(name) > length)
        return name.substring(0, start) + "..." + name.substring(name.length - end, name.length);
    else
        return name;
}

/**
 * 余额不足时候，点击去挣钱，跳转到商城主页
 */
function toMarket() {
    var url = window.location.href;
    if (url.indexOf("192.168.3.67") > 0 || url.indexOf("localhost") > 0) {
        window.location.href = "http://192.168.3.67/Advertiser_Mall/weijifen/home.html";
    } else if (url.indexOf("www.jifenguanggao.com") > 0) {
        window.location.href = "http://www.jifenguanggao.com/Advertiser_Mall/weijifen/home.html";
    } else if (url.indexOf("114.112.104.151") > 0) {
        window.location.href = "http://114.112.104.151/Advertiser_Mall/weijifen/home.html";
    } else {
        window.location.href = "/Lvscore_User_M/userWeb/views/accounterCenter/index.html";
    }
}
//点击确定按钮时，余额不足弹窗消失
function blanceBox(){
    $(".blance").hide();
}